/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.benchmark;

import java.io.File;
import java.util.Properties;
import java.util.StringTokenizer;

import cgl.narada.event.TemplateProfileAndSynopsisTypes;
import cgl.narada.service.ServiceException;
import cgl.narada.service.client.ClientService;
import cgl.narada.service.client.EventConsumer;
import cgl.narada.service.client.EventProducer;
import cgl.narada.service.client.SessionService;
import cgl.narada.util.ConfigurationParamsReader;

/**
   This class is responsible for cycling through the publish rates, message 
   sizes etc specified in the BenchMarkParams file, create the appropriate
   number of publishers and control their publish rates and also the payload
   sizes contained in the messages being published.

   @author Shrideep Pallickara
   $Revision$
   $Date$
*/

public class GaugePublisherController {
  private ClientService clientService;
  private EventConsumer consumer;
  private EventProducer producer;
  
  private GaugePublisher[] publishers;
  private int numOfPublishers;
  private boolean sonicTest = true;

  private int[] messageSizes = {50, 100, 200, 500, 1000, 2000, 5000};
  private int[] virtualpubRates = {1, 5, 10, 50, 100, 200};
  /** The combination of pubRates and numOfMessages at a time, correspond
      directly to the virtual pubRates */
  private int[] pubRates = {1,5, 10, 10/*50*/, 10 /**100*/, 10 /**200*/};
  private int[] numOfMessagesAtATime={1 /*1*/, 1 /*5*/, 1 /*10*/,
			      5 /*50*/, 10 /*100*/, 20 /* 200*/};
  private int numOfMessagesPerTestCase = 1;
  private long sleepTimeBetweenCases= (long)2000;

  private String moduleName = "GaugePublisherController: ";
  
  public GaugePublisherController(int numPublishers,
                                  int numMessagesPerTestCase,
                                  long sleepTimeForCases,
                                  int[] messageSizes ) {
    numOfPublishers = numPublishers;
    numOfMessagesPerTestCase = numMessagesPerTestCase;
    sleepTimeBetweenCases = sleepTimeForCases;
    publishers = new GaugePublisher[numOfPublishers];
    this.messageSizes = messageSizes;
  }

  public void setSonicTest(boolean isSonic) {
    sonicTest = isSonic;
  }

  public void setPublishRateParameters(int[] virtualpubRates, 
				       int[] numOfMessagesAtATime,
				       int[] realPubRates) {
    this.virtualpubRates =  virtualpubRates;
    this.numOfMessagesAtATime = numOfMessagesAtATime;
    pubRates =  realPubRates;
    
    for (int i=0; i < pubRates.length; i++) {
      System.out.println("pubRates[" + i + "]=" + pubRates[i] +
			 ", messagesAtATime[" + i + "]=" +
			 numOfMessagesAtATime[i]);
    }
  }
  
  
  public void initialize(int entityId, Properties props, String commType) 
    throws ServiceException {
    
    clientService = SessionService.getClientService(entityId);
    clientService.initializeBrokerCommunications(props, commType);
  }
  
  
  public void 
  initializeThePublishers(String reportDirectory,
			  int templateId, 
			  int contentSynopsisType, Object contentSynopsis, 
			  int numOfPublishers, Properties pubProperties) 
    throws ServiceException {
    File reportDir = new File(reportDirectory);
    String reportDirLocation = reportDir.getPath();
    if ( (!reportDir.exists()) || (!reportDir.isDirectory())   ) {
      throw new ServiceException(moduleName + "The specified reports directory"
				 + "[" + reportDirLocation + "] does not exist"
				 + ". Please check this.");
    }
    
    for (int i=0; i < numOfPublishers; i++) {
      String pubFileName = reportDirLocation + "/PubRates-Pub" + i + ".txt";
      publishers[i] = 
	new GaugePublisher(clientService, templateId,
			   contentSynopsisType, contentSynopsis,  
			   pubProperties, pubFileName);
      
    } /*end (for)*/
  }
  
  
  public void startPublishing(int numOfMessages, int msgSize, 
			      int numOfMessagesAtATime,
			      int pubRate, int benchMarkTracker) {
    System.out.println(moduleName + "Starting Test Case (" + 
		       benchMarkTracker +")" + 
		       " NumOfMessages=" + numOfMessages + ", MessageSize=" +
		       msgSize + ", MessagesAtATime=" + numOfMessagesAtATime); 
    
    for (int i=0; i<numOfPublishers; i++) {
      publishers[i].publishMessages(numOfMessages, msgSize, pubRate, 
				    numOfMessagesAtATime, benchMarkTracker);
    }
  }
  
  public void proceedToGauge() {
    int benchMarkTracker=0; /** Keeps track of the case being benchMarked */
    for (int i=0; i< pubRates.length; i++) {
      for (int j=0; j< messageSizes.length; j++) {
	benchMarkTracker++;
	startPublishing(numOfMessagesPerTestCase, messageSizes[j], 
			numOfMessagesAtATime[i], 
			pubRates[i],
			benchMarkTracker);
	try {
	  Thread.currentThread().sleep(sleepTimeBetweenCases);
	} catch (InterruptedException ie) {
	  ie.printStackTrace();
	}
      }/**loop(j)*/
      
      try {
	Thread.currentThread().sleep(sleepTimeBetweenCases);
      } catch (InterruptedException ie) {
	ie.printStackTrace();
      }
    }/**loop(i)*/
  }

  public static void main(String[] args) {
    String module = "GaugePublisherController.main()->";
    String gaugeParamsFile = "GaugeParams.txt";

    if ( (args.length < 2) || (! args[0].equals("-f")) ) {
      System.out.println(module + "Usage Options: \n" + 
			 "java cgl.narada.benchmark.GaugePublisherController" +
			 "-f <gaugeParamsFile> \n" );
      System.exit(0);
    } else {
      gaugeParamsFile=args[1];
    }

    System.out.println(module + "Using file [" +  gaugeParamsFile + 
		       "] for initialization of benchmark.");

    ConfigurationParamsReader bmProperties = 
      new ConfigurationParamsReader(gaugeParamsFile);    
    
    int numOfMessages = 
      Integer.parseInt(bmProperties.getProperty("NumOfMessagesPerTestCase"));
    int numOfPublishers = 
      Integer.parseInt(bmProperties.getProperty("NumOfPublishers"));
    String sleepTimeBtwnCases = 
      bmProperties.getProperty("SleepTimeBetweenTestCases");
    long sleepTime = Long.parseLong(sleepTimeBtwnCases);
    
    String sizes = bmProperties.getProperty("MessageSizes");
    StringTokenizer tok = new StringTokenizer(sizes, ",[] ");
    int numTokens = tok.countTokens();
    int[] messageSizes = new int[numTokens];
    for (int i=0; i<numTokens; i++) {
      messageSizes[i] = Integer.parseInt(tok.nextToken().trim());
    }
    

    String vPubRates = bmProperties.getProperty("VirtualPublishRates");
    String numMsgsAtATime = bmProperties.getProperty("NumOfMessagesAtATime");
    String rPubRates = bmProperties.getProperty("RealPublishRates");
    
    tok = new StringTokenizer(vPubRates, ",[] ");
    numTokens = tok.countTokens();
    int[] virtualpubRates = new int[numTokens];
    for (int i=0; i<numTokens; i++) {
      virtualpubRates[i] = Integer.parseInt(tok.nextToken().trim());
    }
    
    tok =  new StringTokenizer(numMsgsAtATime, ",[] ");
    numTokens = tok.countTokens();
    int[] numOfMessagesAtATime = new int[numTokens];
    for (int i=0; i<numTokens; i++) {
      numOfMessagesAtATime[i] = Integer.parseInt(tok.nextToken().trim());
      System.out.println(numOfMessagesAtATime[i]);
    }
    
    tok = new StringTokenizer(rPubRates, ",[] ");
    numTokens = tok.countTokens();
    int[] realPubRates = new int[numTokens];
    for (int i=0; i<numTokens; i++) {
      realPubRates[i] = Integer.parseInt(tok.nextToken().trim());
    }
    
    
    GaugePublisherController bmpc = 
      new GaugePublisherController(numOfPublishers, numOfMessages, sleepTime,
				   messageSizes);
    bmpc.setSonicTest(false);
    bmpc.setPublishRateParameters(virtualpubRates, numOfMessagesAtATime,
				  realPubRates);

    String brokerHost = bmProperties.getProperty("BROKER-HOST");
    String brokerPort= bmProperties.getProperty("BROKER-PORT");
    Properties props = new Properties();
    props.put("hostname", brokerHost); 
    props.put("portnum", brokerPort);
    props.put("UDPListenerPort", "5000");
    String commType =  bmProperties.getProperty("COMM-TYPE");
    int entityId = Integer.parseInt(bmProperties.getProperty("PubEntityId"));
    int templateId = Integer.parseInt(bmProperties.getProperty("TemplateId"));
    
    int contentSynopsisType = TemplateProfileAndSynopsisTypes.STRING;
    Object contentSynopsis = "Test/benchmark";

    String reportsDirectory = bmProperties.getProperty("ReportsDirectory");
    
    Properties pubProperties = new Properties();
    String reliableDelivery = bmProperties.getProperty("ReliableDelivery");
    
    if (reliableDelivery.equals("true") ) {
      pubProperties.setProperty("ReliableDelivery", "true");
    } else {
      pubProperties.setProperty("ReliableDelivery", "false");
    }
    
    try {
      bmpc.initialize(entityId, props, commType);
      bmpc.initializeThePublishers(reportsDirectory,
				   templateId, contentSynopsisType, 
				   contentSynopsis, numOfPublishers,
				   pubProperties);
      bmpc.proceedToGauge();
    } catch (ServiceException serEx) {
      System.out.println("\n\n\n"+ module + 
			 "Error while performing benchmarks " +	 serEx);
    }
    
  }/*end - main */
}/*end -class*/


